package com.suyunyou.spider.utils;

import java.util.Date;
import java.util.List;

import com.suyunyou.manager.pojo.SpiderSite;
import com.system.comm.utils.FrameStringUtil;
import com.system.comm.utils.FrameTimeUtil;

/**
 * 刷新网站入口页的规则处理类
 * @author yuejing
 * @date 2019年1月23日 下午5:19:37
 */
public class RefreshRuleUtil {

	private static final String INTERVAL_MIN = "interval-min:";
	private static final String INTERVAL_HOUR = "interval-hour:";
	private static final String FIXED_HOUR = "fixed-hour:";
	
	/**
	 * 判断当前时间是否在执行时间内容
	 * @param site
	 * @param handleTime 
	 * @return {true:需要执行, false:当前时间不需要执行}
	 */
	public static boolean isHandle(SpiderSite site, Date handleTime) {
		// interval-min:30 (每隔30分钟重新爬入口页)
		Date curDate = getIntervalMin(site);
		if (curDate != null) {
			if (curDate.compareTo(handleTime) <= 0) {
				return true;
			}
			return false;
		}
		// interval-hour:1 (每隔1小时重新爬入口页)
		curDate = getIntervalHour(site);
		if (curDate != null) {
			if (curDate.compareTo(handleTime) <= 0) {
				return true;
			}
			return false;
		}
		// fixed-hour:9:30,12:40 (9点30分和12点40分重新爬入口页)
		curDate = getFixedHour(site, handleTime);
		if (curDate != null) {
			return true;
		}
		return false;
	}

	/**
	 * fixed-hour:9:30,12:40 (9点30分和12点40分重新爬入口页)
	 * @param site
	 * @param handleTime 
	 * @return
	 */
	private static Date getFixedHour(SpiderSite site, Date handleTime) {
		String rule = site.getRule();
		if (rule.startsWith(FIXED_HOUR)) {
			String num = rule.substring(FIXED_HOUR.length());
			List<String> numList = FrameStringUtil.toArray(num, ",");
			for (String str : numList) {
				Date date = FrameTimeUtil.parseDate(FrameTimeUtil.getTodayYyyyMmDd() + " " + str, "yyyy-MM-dd HH:mm");
				String handleDateStr = FrameTimeUtil.parseString(handleTime, "yyyy-MM-dd HH:mm");
				String curDateStr = FrameTimeUtil.parseString(date, "yyyy-MM-dd HH:mm");
				if (handleDateStr.equals(curDateStr)) {
					return date;
				}
			}
		}
		return null;
	}

	/**
	 * interval-hour:1 (每隔1小时重新爬入口页)
	 * @param site
	 * @return
	 */
	private static Date getIntervalHour(SpiderSite site) {
		String rule = site.getRule();
		if (rule.startsWith(INTERVAL_HOUR)) {
			if (site.getRuleTime() == null) {
				return FrameTimeUtil.getTime();
			}
			int num = Integer.valueOf(rule.substring(INTERVAL_HOUR.length()));
			Date date = FrameTimeUtil.addHours(site.getRuleTime(), num);
			return date;
		}
		return null;
	}

	/**
	 * interval-min:30 (每隔30分钟重新爬入口页)
	 * @param site
	 * @return
	 */
	private static Date getIntervalMin(SpiderSite site) {
		String rule = site.getRule();
		if (rule.startsWith(INTERVAL_MIN)) {
			if (site.getRuleTime() == null) {
				return FrameTimeUtil.getTime();
			}
			int num = Integer.valueOf(rule.substring(INTERVAL_MIN.length()));
			Date date = FrameTimeUtil.addMinutes(site.getRuleTime(), num);
			return date;
		}
		return null;
	}

}
